import urllib
import re

LOCATION_URL = 'http://www.checkip.org'
word_with_spaces_regex = '([A-Za-z]+(\s*))*'
two_letter_cap_regex = '[A-Z][A-Z]'
decimal_number_regex = '(-?)[0-9]+(\.([0-9]+))'
city_start = 'City:'
state_start = 'State:'
latitude_start = 'Latitude:'
longitude_start = 'Longitude:'


def getLocation():
  location = {}
  html = urllib.urlopen(LOCATION_URL).readlines()
  for line in html:
    city_index = line.find(city_start)
    state_index = line.find(state_start)
    latitude_index = line.find(latitude_start)
    longitude_index = line.find(longitude_start)
    if city_index > 0:
      city = line[city_index + len(city_start):]
      match = re.search(word_with_spaces_regex, city.strip())
      if match:
        location['city'] = match.group(0).strip()
    if state_index > 0:
      state = line[state_index + len(state_start):]
      match = re.search(two_letter_cap_regex, state.strip())
      if match:
        location['state'] = match.group(0).strip()
    if latitude_index > 0:
      latitude = line[latitude_index + len(latitude_start):]
      match = re.search(decimal_number_regex, latitude.strip())
      if match:
        location['latitude'] = float(match.group(0).strip())
    if longitude_index > 0:
      longitude = line[longitude_index + len(longitude_start):]
      match = re.search(decimal_number_regex, longitude.strip())
      if match:
        location['longitude'] = float(match.group(0).strip())
  return location

    

